<template>
  <div class="backend-status">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>后端连接状态</h3>
          <el-button type="primary" size="small" @click="testConnection" :loading="testing">
            <el-icon><Refresh /></el-icon> 测试连接
          </el-button>
        </div>
      </template>
      
      <div class="status-content">
        <div class="status-item">
          <span class="label">API连接状态：</span>
          <span class="status-badge" :class="statusClass">
            {{ statusText }}
          </span>
        </div>
        
        <div class="status-item">
          <span class="label">WebSocket连接：</span>
          <span class="status-badge" :class="wsStatusClass">
            {{ wsStatusText }}
          </span>
        </div>
        
        <div class="message" v-if="message">
          <el-alert :type="messageType" :title="message" :closable="false" show-icon />
        </div>
        
        <div class="connection-details" v-if="showDetails">
          <h4>连接详情</h4>
          <pre>{{ JSON.stringify(details, null, 2) }}</pre>
        </div>
      </div>
      
      <div class="actions">
        <el-button-group>
          <el-button type="primary" size="small" @click="testApi">
            测试API
          </el-button>
          <el-button type="primary" size="small" @click="testWebSocket">
            测试WebSocket
          </el-button>
          <el-button size="small" @click="toggleDetails">
            {{ showDetails ? '隐藏详情' : '显示详情' }}
          </el-button>
        </el-button-group>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { testBackendConnection } from '@/utils'
import { testConnection as testWsConnection } from '@/utils/websocket'

// 状态变量
const apiStatus = ref('unknown') // unknown, connected, disconnected, error
const wsStatus = ref('unknown')  // unknown, connected, connecting, disconnected
const message = ref('')
const messageType = ref('info')
const details = ref({})
const showDetails = ref(false)
const testing = ref(false)

// 计算属性
const statusText = computed(() => {
  switch (apiStatus.value) {
    case 'connected': return '已连接'
    case 'disconnected': return '未连接'
    case 'error': return '连接错误'
    default: return '未知'
  }
})

const statusClass = computed(() => {
  switch (apiStatus.value) {
    case 'connected': return 'success'
    case 'disconnected': return 'warning'
    case 'error': return 'danger'
    default: return 'info'
  }
})

const wsStatusText = computed(() => {
  switch (wsStatus.value) {
    case 'connected': return '已连接'
    case 'connecting': return '连接中...'
    case 'disconnected': return '未连接'
    default: return '未知'
  }
})

const wsStatusClass = computed(() => {
  switch (wsStatus.value) {
    case 'connected': return 'success'
    case 'connecting': return 'warning'
    case 'disconnected': return 'danger'
    default: return 'info'
  }
})

// 测试API连接
const testApi = async () => {
  if (testing.value) return
  
  testing.value = true
  message.value = '正在测试API连接...'
  messageType.value = 'info'
  
  try {
    const result = await testBackendConnection()
    console.log('API连接测试结果:', result)
    
    details.value = result.details
    message.value = result.message
    
    if (result.success) {
      apiStatus.value = 'connected'
      messageType.value = 'success'
    } else {
      apiStatus.value = 'error'
      messageType.value = 'error'
    }
  } catch (error) {
    console.error('API测试出错:', error)
    apiStatus.value = 'error'
    message.value = '测试过程出错: ' + error.message
    messageType.value = 'error'
    details.value = { error: String(error), stack: error.stack }
  } finally {
    testing.value = false
  }
}

// 测试WebSocket连接
const testWebSocket = async () => {
  if (testing.value) return
  
  testing.value = true
  message.value = '正在测试WebSocket连接...'
  messageType.value = 'info'
  wsStatus.value = 'connecting'
  
  try {
    const result = await testWsConnection()
    console.log('WebSocket连接测试结果:', result)
    
    details.value = result
    
    if (result.connected) {
      wsStatus.value = 'connected'
      message.value = 'WebSocket连接成功'
      messageType.value = 'success'
    } else {
      wsStatus.value = 'disconnected'
      message.value = 'WebSocket连接失败: ' + result.message
      messageType.value = 'error'
    }
  } catch (error) {
    console.error('WebSocket测试出错:', error)
    wsStatus.value = 'disconnected'
    message.value = 'WebSocket测试出错: ' + error.message
    messageType.value = 'error'
    details.value = { error: String(error), stack: error.stack }
  } finally {
    testing.value = false
  }
}

// 测试所有连接
const testConnection = async () => {
  if (testing.value) return
  
  testing.value = true
  message.value = '正在测试所有连接...'
  messageType.value = 'info'
  
  try {
    // 先测试API
    await testApi()
    
    // 再测试WebSocket
    await testWebSocket()
    
    // 显示最终结果
    if (apiStatus.value === 'connected' && wsStatus.value === 'connected') {
      message.value = '所有连接正常'
      messageType.value = 'success'
    } else if (apiStatus.value === 'connected') {
      message.value = 'API连接正常，但WebSocket连接失败'
      messageType.value = 'warning'
    } else if (wsStatus.value === 'connected') {
      message.value = 'WebSocket连接正常，但API连接失败'
      messageType.value = 'warning'
    } else {
      message.value = '所有连接均失败，请检查后端服务'
      messageType.value = 'error'
    }
  } catch (error) {
    console.error('连接测试出错:', error)
    message.value = '连接测试过程出错: ' + error.message
    messageType.value = 'error'
  } finally {
    testing.value = false
  }
}

// 切换显示详情
const toggleDetails = () => {
  showDetails.value = !showDetails.value
}

// 组件挂载时执行
onMounted(() => {
  // 自动测试连接
  setTimeout(() => {
    testConnection()
  }, 1000)
})
</script>

<style scoped>
.backend-status {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.status-content {
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.label {
  font-weight: 500;
  color: #606266;
  width: 120px;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
}

.status-badge.success {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.status-badge.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #faecd8;
}

.status-badge.danger {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

.status-badge.info {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #e9e9eb;
}

.message {
  margin: 16px 0;
}

.connection-details {
  margin-top: 16px;
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
}

.connection-details h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #606266;
}

.connection-details pre {
  margin: 0;
  font-family: 'Courier New', Courier, monospace;
  font-size: 12px;
  color: #606266;
  white-space: pre-wrap;
}

.actions {
  margin-top: 16px;
}
</style> 